<?php

namespace App\Models\User;

use App\Jobs\AttachIpAddressJob;
use App\Jobs\User\UserDeleteAfterJob;
use App\Jobs\User\UserWithdrawalProcessJob;
use App\Jobs\UserRegisterAfterJob;
use App\Lib\WeApp\WeApp;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\Settings;
use App\Models\Posts\WxPost;
use App\Wen\Utils\StatisticUtils;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\v1\User\SettingAstroController as AstrosetController;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Scout\Searchable;

class WxUser extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;
    use Searchable;

    protected $appends = ['follow_count','follow_user_count','like_count','is_online'];

    protected $table = 'wx_user';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if($model->weixin_openid === ''){
                $model->weixin_openid = null;
            }
        });

        static::deleting(function ($user) {
            // 在软删除或真实删除前执行的逻辑
            // 例如：记录日志、发送通知等
        });

        static::deleted(function ($user) {
            // 在软删除或真实删除后执行的逻辑
            // 例如：记录日志、发送通知等
            UserDeleteAfterJob::dispatch($user->id);
        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
            if($model->user_name){
                $model->user_name = str_replace([' 🤖', '🤖',' 💙🤖', ' 💗🤖', '💙🤖', '💗🤖'], '', $model->user_name);
            }
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'user_name'){

                }else if($key == 'user_state'){
                    Cache::forget('user:state:'.$model->id);
                }
            }
        });

    }

    public function searchableAs()
    {
        return str_replace('.', '_', str_replace(['https://', 'http://'], '', env('APP_URL', 'minisns.cn'))).'_'.'user_wx_user_index';
    }
    /**
     * 获取模型的可索引的数据。
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();
        $search_data = [
            'id' => $array['id'],
            'user_name' => $array['user_name'],
            'user_introduce' => $array['user_introduce'],
            'user_state' => $array['user_state'],
            'tenant_id' => $array['tenant_id'],
        ];

        return $search_data;
    }

    /**
     * 确定模型是否可搜索
     *
     * @return bool
     */
    public function shouldBeSearchable()
    {
        return ($this->user_state == 0);
    }

    /**
     * @param $data
     * @param string $platform mini,app,mp,web,shop,apple,sms
     * @return int
     */
    public function registerUser($data, $platform = 'mini', $from_user = 0)
    {
        DB::beginTransaction();
        try{
//            _logger_(__file__, __line__, $data);
            global $__MINI_GLOBAL_IP__;
            $openid = _array_key($data, 'openId', null);
            $unionId = _array_key($data, 'unionId', null);
            $phone = _array_key($data, 'phone', null);
            $country_code = _array_key($data, 'country_code', null);
            $device = in_array(_array_key($data, 'device', null), ['app', 'h5', 'mp', 'pc']) ? _array_key($data, 'device', null) : '';
            if($platform == 'sms'){
                // 短信
                if(_empty_($phone) || _empty_($country_code)){
                    DB::rollBack();
                    return 0;
                }
                $phone_user = WxUser::withTrashed()->where([
                    ['phone', '=', $phone], ['country_code', '=', $country_code]
                ])->first();
                if($phone_user){
                    if($phone_user->user_state == 1){
                        // 用户注销
//                    return -1;
                        $phone_user->user_state = 0;
                        $phone_user->save();
                        UserUtils::add_user_notice(4008, $phone_user->id, '账号注销申请已取消', '您好，由于您在注销账号申请的资料保留期内重新登录账号，系统已为您重新激活该账号', 100);
                    }else if($phone_user->user_state == 2){
                        return -3;
                    }
                    UserUtils::set_online($phone_user->id, $device);
                    if ($phone_user->trashed()) {
                        $phone_user->restore();
                    }

                    if($phone_user->ip  != $__MINI_GLOBAL_IP__){
                        $phone_user->ip = $__MINI_GLOBAL_IP__;
                        $phone_user->save();
                        AttachIpAddressJob::dispatch(2, $phone_user->id)->delay(2);
                    }

                    DB::commit();
                    return $phone_user->id;
                }

            }else{
                // 授权登录
                if(_empty_($openid) && _empty_($unionId)){
                    DB::rollBack();
                    return 0;
                }
                if($unionId){
                    // 判断是否已经注册过
                    if($platform == 'qq-app' || $platform == 'qq-web'){
                        $unionid_user = WxUser::withTrashed()->where('qq_unionid',$unionId)->first();
                    }else{
                        $unionid_user = WxUser::withTrashed()->where('weixin_unionid',$unionId)->first();
                    }

                    if($unionid_user){
                        if($platform == 'mini' && _empty_($unionid_user->weixin_openid) && $openid){
                            // 现在只有一种情况，在未配置开放平台的情况下，但进行了公众号登录
                            $repeat_user = WxUser::withTrashed()->where('weixin_openid', $openid)->first(['id', 'user_name']);
                            if($repeat_user){
                                if ($repeat_user->trashed()) {
                                    WxUser::where('id', $repeat_user->id)->forceDelete();
                                    $unionid_user->weixin_openid = $openid;
                                    $unionid_user->save();
                                }else{
                                    if($unionid_user->id > $repeat_user->id){
                                        WxUser::where('id', $repeat_user->id)->update(['weixin_unionid'=> $unionid_user->weixin_unionid]);
                                        WxUser::where('id', $unionid_user->id)->forceDelete();
                                        $unionid_user = WxUser::find($repeat_user->id);
                                    }
                                }
                            }else{
                                $unionid_user->weixin_openid = $openid;
                                $unionid_user->save();
                            }
                        }else if($platform == 'app' && _empty_($unionid_user->weixin_app_openid) && $openid){
                            $repeat_user = WxUser::where('weixin_app_openid', $openid)->first(['id', 'user_name']);
                            if($repeat_user){
                                UserUtils::assistant_notice('admin', '您站内存在同一微信多个账号的问题，这是由于没有及时配置开放平台导致的
                                ，您应该手动删除其中一个，来消除此问题
                                ，重复的站内用户：<a href="/pages/user/user?id='.$unionid_user->id.'">'.$unionid_user->id.'</a>与<a href="/pages/user/user?id='.$repeat_user->id.'">'.$repeat_user->id.'</a>，系统建议您删除'.$repeat_user->id.'的weixin_app_openid字段');
                            }else{
                                $unionid_user->weixin_app_openid = $openid;
                                $unionid_user->save();
                            }
                        }else if($platform == 'mp' && _empty_($unionid_user->weixin_mp_openid) && $openid){
                            try{
                                $unionid_user->weixin_mp_openid = $openid;
                                $unionid_user->save();
                            }catch (\Exception $e){
                                $repeat_user = WxUser::where('weixin_mp_openid', $openid)->first(['id', 'user_name']);
                                UserUtils::assistant_notice('admin', '您站内存在同一微信多个账号的问题，这是由于没有及时配置开放平台导致的，您应该手动删除其中一个，来消除此问题，重复的站内用户：<a href="/pages/user/user?id='.$unionid_user->id.'">'.$unionid_user->id.'</a>与<a href="/pages/user/user?id='.$repeat_user->id.'">'.$repeat_user->id.'</a>');
                            }
                        }else if($platform == 'web' && _empty_($unionid_user->weixin_web_openid) && $openid){
                            try{
                                $unionid_user->weixin_web_openid = $openid;
                                $unionid_user->save();
                            }catch (\Exception $e){
                                $repeat_user = WxUser::where('weixin_web_openid', $openid)->first(['id', 'user_name']);
                                UserUtils::assistant_notice('admin', '您站内存在同一微信多个账号的问题，这是由于没有及时配置开放平台导致的，您应该手动删除其中一个，来消除此问题，重复的站内用户：<a href="/pages/user/user?id='.$unionid_user->id.'">'.$unionid_user->id.'</a>与<a href="/pages/user/user?id='.$repeat_user->id.'">'.$repeat_user->id.'</a>');
                            }
                        }else if($platform == 'shop' && _empty_($unionid_user->weixin_shop_openid) && $openid){
                            try{
                                $unionid_user->weixin_shop_openid = $openid;
                                $unionid_user->save();
                            }catch (\Exception $e){
                                $repeat_user = WxUser::where('weixin_shop_openid', $openid)->first(['id', 'user_name']);
                                UserUtils::assistant_notice('admin', '您站内存在同一微信多个账号的问题，这是由于没有及时配置开放平台导致的，您应该手动删除其中一个，来消除此问题，重复的站内用户：<a href="/pages/user/user?id='.$unionid_user->id.'">'.$unionid_user->id.'</a>与<a href="/pages/user/user?id='.$repeat_user->id.'">'.$repeat_user->id.'</a>');
                            }
                        }

                        if($unionid_user->user_state == 1){
                            // 用户注销
//                    return -1;
                            $unionid_user->user_state = 0;
                            $unionid_user->save();
                            UserUtils::add_user_notice(4008, $unionid_user->id, '账号注销申请已取消', '您好，由于您在注销账号申请的资料保留期内重新登录账号，系统已为您重新激活该账号', 100);
                        }else if($unionid_user->user_state == 2){
                            return -3;
                        }
                        UserUtils::set_online($unionid_user->id, $device);
                        if ($unionid_user->trashed()) {
                            $unionid_user->restore();
                        }

                        if($unionid_user->ip  != $__MINI_GLOBAL_IP__){
                            $unionid_user->ip = $__MINI_GLOBAL_IP__;
                            $unionid_user->save();
                            AttachIpAddressJob::dispatch(2, $unionid_user->id)->delay(2);
                        }

                        DB::commit();
                        return $unionid_user->id;
                    }
                }

                if($openid){
                    $user = null;
                    if($platform == 'app'){
                        $user = WxUser::withTrashed()->where('weixin_app_openid',$openid)->first();
                    }else if($platform == 'mp'){
                        $user = WxUser::withTrashed()->where('weixin_mp_openid',$openid)->first();
                    }else if($platform == 'web'){
                        $user = WxUser::withTrashed()->where('weixin_web_openid',$openid)->first();
                    }else if($platform == 'shop'){
                        $user = WxUser::withTrashed()->where('weixin_shop_openid',$openid)->first();
                    }else if($platform == 'apple'){
                        $user = WxUser::withTrashed()->where('apple_openid',$openid)->first();
                    }else if($platform == 'qq-app'){
                        $user = WxUser::withTrashed()->where('qq_app_openid',$openid)->first();
                    }else if($platform == 'qq-web'){
                        $user = WxUser::withTrashed()->where('qq_web_openid',$openid)->first();
                    }else{
                        $user = WxUser::withTrashed()->where('weixin_openid',$openid)->first();
                    }
                    if($user){
                        $uid = $user->id;
                        $change_flag = false;
                        if($user->user_state == 1){
                            $user->user_state = 0;
                            $change_flag = true;
                            UserUtils::add_user_notice(4008, $user->id, '账号注销申请已取消', '您好，由于您在注销账号申请的资料保留期内重新登录账号，系统已为您重新激活该账号', 100);
                        }else if($user->user_state == 2){
                            return -3;
                        }
                        if ($user->trashed()) {
                            $user->restore();
                        }
                        if($platform != 'apple'){
                            if(_empty_($user->weixin_unionid) && $unionId){
                                $change_flag = true;
                                $user->weixin_unionid = $unionId;
                            }
                        }

                        if($user->ip != $__MINI_GLOBAL_IP__){
                            $user->ip = $__MINI_GLOBAL_IP__;
                            AttachIpAddressJob::dispatch(2, $user->id)->delay(2);
                        }

                        if($change_flag){
                            $user->save();
                        }
                        UserUtils::set_online($uid, $device);

                        DB::commit();
                        return $uid;
                    }
                }
            }

            $app_register_style = Utils::get_login_styles(0);
            if(_empty_($app_register_style)){
//                DB::rollBack();
//                return 0;
                $app_register_style = [0];
            }


            $data['nickName'] = trim($data['nickName']);
            while (WxUser::where('user_name',$data['nickName'])->exists()){
                $data['nickName'] .= '_'.mt_rand(1, 1000);
            }
//        $maxId = WxUser::max('id');
            $user = new WxUser();
            $user->weixin_unionid=null;
            $user->weixin_openid=null;
            $user->weixin_app_openid=null;
            $user->weixin_mp_openid=null;
            $user->weixin_web_openid=null;
            $user->weixin_shop_openid=null;
            $user->apple_openid=null;
            $user->phone = '';
            $user->country_code = null;
            $user->email = '';
            if($platform == 'mini'){
                if(!in_array(0, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->weixin_openid=$openid;
            }else if($platform == 'app'){
                if(!in_array(0, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->weixin_app_openid=$openid;

                $process_url = ImageUtils::upload_url_img($data['avatarUrl']);
                if($process_url && _array_key($process_url, 'url', '') ){
                    $data['avatarUrl'] = _array_key($process_url, 'url', '');
                }else{
                    $data['avatarUrl'] = Settings::get('img_default_avatar', '');
                }

            }else if($platform == 'mp'){
                if(!in_array(0, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->weixin_mp_openid=$openid;

                $process_url = ImageUtils::upload_url_img($data['avatarUrl']);
                if($process_url && _array_key($process_url, 'url', '') ){
                    $data['avatarUrl'] = _array_key($process_url, 'url', '');
                }else{
                    $data['avatarUrl'] = Settings::get('img_default_avatar', '');
                }

                if(_empty_($unionId)){
                    $weapp = new WeApp('mp');
                    if($weapp){
                        $mpServicer = $weapp->getMpServicer();
                        if($mpServicer){
                            $info_res = $mpServicer->getUserInfo($openid);
                            if($info_res['code'] == 200 && _array_key($info_res, 'unionid', '')){
                                $unionId = $info_res['unionid'];
                            }
                        }
                    }
                }

            }else if($platform == 'web'){
                if(!in_array(0, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->weixin_web_openid=$openid;

                $process_url = ImageUtils::upload_url_img($data['avatarUrl']);
                if($process_url && _array_key($process_url, 'url', '') ){
                    $data['avatarUrl'] = _array_key($process_url, 'url', '');
                }else{
                    $data['avatarUrl'] = Settings::get('img_default_avatar', '');
                }

            }else if($platform == 'shop'){
                if(!in_array(0, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->weixin_shop_openid=$openid;

                $process_url = ImageUtils::upload_url_img($data['avatarUrl']);
                if($process_url && _array_key($process_url, 'url', '') ){
                    $data['avatarUrl'] = _array_key($process_url, 'url', '');
                }else{
                    $data['avatarUrl'] = Settings::get('img_default_avatar', '');
                }

            }else if($platform == 'apple'){
                if(!in_array(1, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->apple_openid=$openid;
            }else if($platform == 'qq-app'){
                if(!in_array(3, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->qq_app_openid=$openid;

                $process_url = ImageUtils::upload_url_img($data['avatarUrl']);
                if($process_url && _array_key($process_url, 'url', '') ){
                    $data['avatarUrl'] = _array_key($process_url, 'url', '');
                }else{
                    $data['avatarUrl'] = Settings::get('img_default_avatar', '');
                }

            }else if($platform == 'qq-web'){
                if(!in_array(3, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                $user->qq_web_openid=$openid;

                $process_url = ImageUtils::upload_url_img($data['avatarUrl']);
                if($process_url && _array_key($process_url, 'url', '') ){
                    $data['avatarUrl'] = _array_key($process_url, 'url', '');
                }else{
                    $data['avatarUrl'] = Settings::get('img_default_avatar', '');
                }

            }else if($platform == 'sms'){
                if(!in_array(2, $app_register_style)){
                    DB::rollBack();
                    return -2;
                }
                if(_empty_($phone) || _empty_($country_code)){
                    DB::rollBack();
                    return 0;
                }
                $user->phone = $phone;
                $user->country_code = $country_code;
            }
            if( $platform == 'apple' || $platform == 'sms' ){
                $user->weixin_unionid = null;
            }else if($unionId){
                if($platform == 'qq-app' || $platform == 'qq-web'){
                    $user->qq_unionid = $unionId;
                }else{
                    $user->weixin_unionid = $unionId;
                }
            }
            $user->user_introduce = null;
            $user->user_name=$data['nickName'];
            $user->weixin_name=$data['nickName'];
            $user->user_background_maps = $data['user_background_maps'] ?? Settings::get('user_background_maps');
            $user->user_avatar= _array_key($data, 'avatarUrl', Settings::get('img_default'));
            $user->country=$data['country'] ?? '';
            $user->province=$data['province'] ?? '';
            $user->city=$data['city'] ?? '';
            // [0 => '未知',1 => '男',2 => '女']
            $user->gender=$data['gender'] ?? 0;
            if($from_user && (int)$from_user > 0){
                $user->who = (int)$from_user;
            }
            if($__MINI_GLOBAL_IP__){
                $user->ip = $__MINI_GLOBAL_IP__;
            }

            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $user->tenant_id = $__MINI_GLOBAL_TENANT_ID__;
            }

            if(_array_key($data, 'user_introduce', '')){
                $user->user_introduce = _array_key($data, 'user_introduce', '');
            }

            $r = $user->save();
            //新增星盘配置初始化，注册调用
            $set = new AstrosetController();
            $set->init($user->id);
            if($r){
                $user_setting = new WxUserSetting();
                $user_setting->user_id = $user->id;
                $user_setting->save();
                DB::commit();

                $this->register_after($user, $from_user);

                return $user->id;
            }
            DB::rollBack();
            return 0;
        }catch (\Exception $e){
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return 0;
        }
    }


    public function register_after(WxUser &$user, $from_user_id){
        global $__MINI_GLOBAL_IP__, $__MINI_GLOBAL_DEVICE__;
        UserUtils::set_online($user->id, $__MINI_GLOBAL_DEVICE__);
        UserRegisterAfterJob::dispatch($user->id);
        if($__MINI_GLOBAL_IP__){
            AttachIpAddressJob::dispatch(2, $user->id)->delay(2);
        }
        global $__MINI_GLOBAL_PAYCODE_20__;
        if($__MINI_GLOBAL_PAYCODE_20__){
            $itc_id = 0;
            if(is_string($from_user_id) && StrUtils::startsWith($from_user_id,'itc')){
                $itc_temp_code = WxUserInviteTempCode::find((int)str_replace('itc', '', $from_user_id));
                if($itc_temp_code){
                    $itc_id = $itc_temp_code->id;
                    if(!_empty_($itc_temp_code->user_id)){
                        $from_user_id = $itc_temp_code->user_id;
                        WxUser::where('id', $user->id)->update(['who'=>$from_user_id]);
                    }
                }else{
                    $from_user_id = 0;
                }
            }
            if($from_user_id && (int)$from_user_id > 0) {
                if(UserUtils::user_permissions_check_by_config($from_user_id, 'user_invite_immediately_benefit_white_list')){
                    $from_user_obj = WxUser::find($from_user_id);
                    if($from_user_obj && $from_user_obj->user_state === 0 && ($from_user_obj->invite_benefit == -1 || $from_user_obj->invite_benefit > 0)){
                        $inviter_benefit_coins = Settings::get('user_invite_immediately_benefit_coins', 0);
                        if($from_user_obj->invite_benefit == -1){
                            $inviter_benefit_blance = round(Settings::get('user_invite_immediately_benefit_blance', 0.0), 2);
                        }else{
                            $inviter_benefit_blance = $from_user_obj->invite_benefit;
                        }

                        DB::beginTransaction();
                        try {
                            // todo:
                            if ($inviter_benefit_coins > 0) {
                                UserUtils::update_user_coins($from_user_id, 22, $inviter_benefit_coins, '您推广了一位「<a href="/pages/user/user?id='.$user->id.'">新用户 id:'.$user->id.'</a>」，收到系统奖励：'.Settings::get('app_coin_name', '硬币').'+'.$inviter_benefit_coins);
                            }
                            if($inviter_benefit_blance >= 0.01){
                                UserUtils::update_user_financial($from_user_id, 24, $inviter_benefit_blance, '您推广了一位「<a href="/pages/user/user?id='.$user->id.'">新用户 id:'.$user->id.'</a>」，收到系统奖励：余额￥'.$inviter_benefit_blance);
                                if(Settings::get('user_invite_immediately_benefit_auto_withdrawal') == 1 && !_empty_($from_user_obj->weixin_openid)){
                                    $r = UserUtils::update_user_financial($from_user_obj->id, 2, $inviter_benefit_blance, '发起余额提现￥'.$inviter_benefit_blance, 0, '', '');
                                    if($r){
                                        $userfinancial = WxUserFinancial::where('user_id', $from_user_obj->id)->first();
                                        $withdrawal_id = Utils::getSn(14);
                                        // 提现记录
                                        $userWithdrawalModel = new WxUserWithdrawal();
                                        $userWithdrawalModel->user_id = $from_user_obj->id;
                                        $userWithdrawalModel->withdrawal_id = $withdrawal_id;
                                        $userWithdrawalModel->price = $inviter_benefit_blance;
                                        $userWithdrawalModel->pay_amount = $inviter_benefit_blance;
                                        $userWithdrawalModel->bank_name = '';
                                        $userWithdrawalModel->bank_card = '';
                                        if($userfinancial){
                                            $userWithdrawalModel->real_name = $userfinancial->real_name;
                                            $userWithdrawalModel->wechat_phone = $userfinancial->wechat_phone;
                                        }
                                        $userWithdrawalModel->alipay_phone = null;
                                        $userWithdrawalModel->withdrawal_remark = '邀请用户(id: '.$user->id.')即时奖励';
                                        $userWithdrawalModel->withdrawal_scene = 1;
                                        $userWithdrawalModel->state = 0;
                                        $userWithdrawalModel->save();
                                        UserUtils::assistant_notice('admin', '有用户（<a href="/pages/user/user?id='.$from_user_obj->id.'">id: '.$from_user_obj->id.'</a>）提交了提现（来自分享裂变-自动打款）。');
                                        UserWithdrawalProcessJob::dispatch($userWithdrawalModel->id);
                                    }
                                }
                            }

                            if($itc_id > 0){
                                $itc_record = new WxUserInviteTempCodeRecord();
                                $itc_record->itc_id = $itc_id;
                                $itc_record->user_id = $from_user_id;
                                $itc_record->object_id = $user->id;
                                $itc_record->reward_balance = $inviter_benefit_blance >= 0.01 ? $inviter_benefit_blance : 0;
                                $itc_record->reward_coin = $inviter_benefit_coins > 0 ? $inviter_benefit_coins : 0;
                                $itc_record->save();
                            }

                            DB::commit();
                            return true;
                        } catch (\Exception $e) {
                            DB::rollBack();
                            _logger_(__file__, __line__, $e->getMessage());
                            return false;
                        }
                    }
                }
            }
        }
    }


    public function posts()
    {
        return $this->belongsTo(WxPost::class,'id','user_id');
    }


    public function userFollow()
    {
        return $this->hasMany(WxUser::class,'user_follow_id','id');
    }


    public function getUserNameAttribute($value)
    {
        global $__MINI_GLOBAL_REQUEST_ENV__;
        if($__MINI_GLOBAL_REQUEST_ENV__ == 'web'){
            if($this->is_robot > 0){
                if($this->gender == 1){
                    return $value.' 💙🤖';
                }else if($this->gender == 2){
                    return $value.' 💗🤖';
                }else{
                    return $value.' 🤖';
                }

            }
        }
        return $value;
    }
    /**
     * 关注数量
     * @param $uid
     * @return mixed
     */
    public function getFollowCountAttribute()
    {
        $uid = $this->id;
        return StatisticUtils::user_follow_count($uid);
    }

    /**
     * 粉丝数量
     * @param $uid
     */
    public function getFollowUserCountAttribute()
    {
        $uid = $this->id;
        return StatisticUtils::user_fans_count($uid);
    }

    /**
     * 获赞👍数量
     * @param $uid
     * @return mixed
     */
    public function getLikeCountAttribute()
    {
        $uid = $this->id;
        return StatisticUtils::user_beliked_count($uid);
    }

//    public function setUserNameAttribute($value)
//    {
//        return base64_encode($value);
//    }
//
//    public function setWeixinNameAttribute($value)
//    {
//        return base64_encode($value);
//    }


    public function getUserIntroduceAttribute($value)
    {
        return $value ?: Settings::get('app_user_introduce', '这个人很懒，还没有简介');
    }

    public function getUserAvatarAttribute($value)
    {
        return $value ?: Settings::get('img_default_avatar', 'https://img.mini.minisns.cn/images/avatar.png');
    }

    public function getIsMemberAttribute($value)
    {
        return ((int)$value >= time()) ? 1 : 0;
    }

    public function getIsOnlineAttribute()
    {
        return Cache::has('websocket:uid2clientid:'.$this->id);
    }

    public function getPhoneAttribute($value)
    {
        if($value){
            return substr($value, 0, 3) .'********';
        }else{
            return '';
        }

    }

    public function getInviteCountAttribute(){
        return WxUser::where('who', $this->id)->count();
    }

    public function getUserBirthdayAttribute($v)
    {
        if($v == '请选择'){
            return '';
        }
        return $v;
    }

    public function getIpAddressAttribute()
    {
        if($this->country) {
            $show = Settings::get('app_ip_user_show', 3);
            if ($show == 0) {
                return '';
            } else if ($show == 1) {
                return $this->country;
            } else if ($show == 2) {
                return $this->province;
            } else if ($show == 3) {
                return $this->city;
            } else if ($show == 4) {
                return $this->district;
            }
        }
        return '';
    }

    public function online()
    {
        return $this->hasOne(WxUserOnline::class,'user_id','id');
    }

}